﻿using DevelopTool.Bll.LocalDbBlls;
using DevelopTool.Common;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.CommonHelpers;
using DevelopTool.Model.Enums;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace DevelopTool.Forms.SafetyForms
{
    /// <summary>
    /// 锁屏窗体
    /// </summary>
    public partial class LockForm : BaseUIForm
    {
        /// <summary>
        /// 确认标志
        /// </summary>
        public bool IsConfirm { get; set; } = false;

        private Color defaultColor;

        private Color errorColor;

        private LocalUserBll localUserBll;

        /// <summary>
        /// 拥有此窗体的父窗体
        /// </summary>
        private UIForm ownerForm;

        /// <summary>
        /// 窗口标题
        /// </summary>
        private string formTitle;


        /// <summary>
        /// 密码错误次数
        /// </summary>
        private int pwdErrorCount;


        public LockForm(UIForm ownerForm)
        {
            InitializeComponent();
            this.ownerForm = ownerForm;
        }

        private void LockForm_Load(object sender, EventArgs e)
        {
            formTitle = Text;
            localUserBll = new LocalUserBll();

            SetTitleLockTime();//设置标题时间

            defaultColor = textPassword.RectColor;
            errorColor = Color.Red;

            uiToolTip.SetToolTip(btnUnLock, "奔跑吧少年~");
            uiToolTip.SetToolTip(btnOut, "不想用了？再见啦？");

            Activate();
            textPassword.Focus();


            //如果主窗口是最小化，那么锁屏窗口也设为最小化
            if (ownerForm.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = ownerForm.WindowState;
            }

            if (!ownerForm.Visible)
            {
                this.Hide();
            }
            IsConfirm = false;//默认是未确认

            ThemHelper.SetSystemThem(this);

            if (Setting.System.SendMsgModule.Contains("Lock"))
                FeiShuMsgHelper.SendCardMsgAsync(string.Empty, "锁定");
        }


        /// <summary>
        /// 在窗口标题显示锁定的时间
        /// </summary>
        private void SetTitleLockTime()
        {
            Stopwatch formShowTime = new Stopwatch();
            formShowTime.Start();

            Timer timer = new Timer
            {
                Interval = 1000,
                Enabled = true
            };
            timer.Tick += delegate (object sender, EventArgs e)
            {
                var time = formShowTime.Elapsed;
                Text = formTitle + $"({Convert.ToInt32(time.TotalHours)}:{time.Minutes}:{time.Seconds})";
            };
        }


        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUnLock_Click(object sender, EventArgs e)
        {
            if (!base.CheckData(textPassword,"请输入密码"))
            {
                textPassword.Focus();
                return;
            }

            var tuple = localUserBll.UnLock(textPassword.Text);//解锁逻辑

            if (tuple.Item1 == 1)//解锁成功
            {
                if (Setting.System.SendMsgModule.Contains("Lock"))
                    FeiShuMsgHelper.SendCardMsgAsync(string.Empty, "解锁");

                IsConfirm = true;
                this.ShowSuccessTip(tuple.Item2);
            }
            else if (tuple.Item1 == 0)//密码错误
            {
                this.ShowErrorTip(this.textPassword, tuple.Item2);
                pwdErrorCount++;
                if (pwdErrorCount >= new Random(Guid.NewGuid().GetHashCode()).Next(5, 20))
                {
                    if (Setting.System.SendMsgModule.Contains("Lock"))
                        FeiShuMsgHelper.SendCardMsgAsync(string.Empty, $"解锁-密码错误次数超过{pwdErrorCount}", LogType.Warning);

                    this.ShowWarningDialog("思考时间", "密码错误次数太多了，休息会，喝杯咖啡再试吧！");
                    pwdErrorCount = 0;

                }
            }
            else//其它情况
            {
                this.ShowErrorDialog(tuple.Item2);
            }
        }



        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOut_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog($"{GlobalData.AppName_zh}-重要提示", "是否确定退出，记得保存数据！", UIStyle.Orange))
            {
                base.ExitApp();
            }
        }


        private void textPassword_TextChanged(object sender, EventArgs e)
        {
            base.TextBoxTextChanged(sender, e);
        }


        /// <summary>
        /// 窗体关闭前事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LockForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.ShowWarningTip("解锁后才能关闭哦~");

            e.Cancel = true;
        }

        private void LockForm_VisibleChanged(object sender, EventArgs e)
        {
            if (this.Visible)
            {
                //绑定动画
                AnimatorHelper.BindShowAnimator(new List<Control>() {
                    { this.btnUnLock},
                    { this.btnOut}
                });
            }
        }

        private void LockForm_ExtendBoxClick(object sender, EventArgs e)
        {
            AboutHelper.ShowAbout();
        }
    }
}
